/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mydomain.debtbook;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;

/**
 * Demonstrates expandable lists backed by Cursors
 */
public class EditDebtActivity extends Activity {

	private ContactAccessor mContactAccessor;
	private DebtAdapter debtAdapter;
	private Cursor debtCursor;
	private ContactInfo selectedContact;

	private EditText lenderEdit;
	private EditText borrowerEdit;
	private EditText debtAmountEdit;
	private EditText categoryEdit;
	private EditText descriptionEdit;
	private EditText dateEdit;

	private ImageView expandLender;
	private ImageView expandDebtAmount;
	private ImageView expandBorrower;
	private ImageView expandCategory;
	private ImageView expandDescription;
	private ImageView expandDate;

	private Button saveOrEdit;
	private Button back;

	private String missing;
	private String debtId;
	private boolean isEdit;

	private static final int LENDER_REQUEST = 0;
	private static final int BORROWER_REQUEST = 1;
	private static final int CATEGORY_REQUEST = 2;

	private static final int MY_ERROR_DIALOG = 0;
	private static final int MY_DATE_PICKER_DIALOG = 1;

	private String strDate;

	private OnClickListener myClickListener;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			debtId = extras.getString("DEBT_ID");
		}
		isEdit = false;
		intitalizeAccessors();
		initalizeView();
		initalizeListener();
	}

	private void intitalizeAccessors() {
		mContactAccessor = ContactAccessor.getInstance();
		debtAdapter = ((debtBookApplication) this.getApplication())
				.getDatabaseAdapter();
	}

	private void initalizeView() {
		setContentView(R.layout.edit_debt);
		lenderEdit = (EditText) findViewById(R.id.ed_lenderEdit);
		borrowerEdit = (EditText) findViewById(R.id.ed_borrowerEdit);
		debtAmountEdit = (EditText) findViewById(R.id.ed_debtAmountEdit);
		categoryEdit = (EditText) findViewById(R.id.ed_categoryEdit);
		descriptionEdit = (EditText) findViewById(R.id.ed_descriptionEdit);
		dateEdit = (EditText) findViewById(R.id.ed_dateEdit);

		expandLender = (ImageView) findViewById(R.id.ed_expandLender);
		expandDebtAmount = (ImageView) findViewById(R.id.ed_expandDebtAmount);
		expandBorrower = (ImageView) findViewById(R.id.ed_expandBorrower);
		expandCategory = (ImageView) findViewById(R.id.ed_expandCategory);
		expandDescription = (ImageView) findViewById(R.id.ed_expandDescription);
		expandDate = (ImageView) findViewById(R.id.ed_expandDate);

		saveOrEdit = (Button) findViewById(R.id.ed_saveOrEditButton);
		back = (Button) findViewById(R.id.ed_backButton);
		dateEdit.setText(DateFormat.getDateInstance().format(
				Calendar.getInstance().getTime()));

		Cursor editDebtCursor = debtAdapter.getDebtByIdCursor(debtId);
		editDebtCursor.moveToFirst();
		lenderEdit.setText(editDebtCursor.getString(editDebtCursor
				.getColumnIndex(DebtAdapter._LENDER)));
		borrowerEdit.setText(editDebtCursor.getString(editDebtCursor
				.getColumnIndex(DebtAdapter._BORROWER)));
		debtAmountEdit.setText(editDebtCursor.getString(editDebtCursor
				.getColumnIndex(DebtAdapter._DEBT)));
		categoryEdit.setText(editDebtCursor.getString(editDebtCursor
				.getColumnIndex(DebtAdapter._CATEGORY)));
		descriptionEdit.setText(editDebtCursor.getString(editDebtCursor
				.getColumnIndex(DebtAdapter._DESCRIPTION)));
		dateEdit.setText(editDebtCursor.getString(editDebtCursor
				.getColumnIndex(DebtAdapter._CREATE_DATE)));
		// lenderEdit.setFocusable(false);
		lenderEdit.setEnabled(false);

		borrowerEdit.setEnabled(false);
		debtAmountEdit.setEnabled(false);
		categoryEdit.setEnabled(false);
		descriptionEdit.setEnabled(false);
		dateEdit.setEnabled(false);

	}

	private void initalizeListener() {
		myClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (v == expandLender) {
					pickContact(LENDER_REQUEST);
				} else if (v == expandBorrower) {
					pickContact(BORROWER_REQUEST);
				} else if (v == expandDebtAmount) {
					showDebtPicker();
				} else if (v == expandCategory) {
					showCategoryPicker();
				} else if (v == expandDescription) {
					showDescriptionPicker();
				} else if (v == expandDate) {
					showDialog(MY_DATE_PICKER_DIALOG);
				} else if (v == saveOrEdit) {

					if (isEdit) {

						updateDebt();
						finish();

					} else {
						editDebt();

					}

				} else if (v == back) {
					finish();
				}

			}
		};

		saveOrEdit.setOnClickListener(myClickListener);
		back.setOnClickListener(myClickListener);

	}

	public void setClickListener() {
		expandLender.setOnClickListener(myClickListener);
		expandBorrower.setOnClickListener(myClickListener);
		expandDebtAmount.setOnClickListener(myClickListener);
		expandDescription.setOnClickListener(myClickListener);
		expandCategory.setOnClickListener(myClickListener);
	}

	private void clearFields() {

		lenderEdit.setText("");
		borrowerEdit.setText("");
		debtAmountEdit.setText("");
		descriptionEdit.setText("");
	}

	private void showCategoryPicker() {
		startActivityForResult(new Intent(this, ListCategoryActivity.class),
				CATEGORY_REQUEST);
	}

	private void showDescriptionPicker() {

	}

	private void showDebtPicker() {

	}

	private void editDebt() {
		setClickListener();
		setEditable();
	}

	private void setEditable() {
		lenderEdit.setEnabled(true);
		borrowerEdit.setEnabled(true);
		debtAmountEdit.setEnabled(true);
		categoryEdit.setEnabled(true);
		descriptionEdit.setEnabled(true);
		dateEdit.setEnabled(true);
		saveOrEdit.setText(R.string.save);
		isEdit = true;
	}

	private void updateDebt() {

		String lender = lenderEdit.getText().toString();
		String borrower = borrowerEdit.getText().toString();
		String debt = debtAmountEdit.getText().toString();
		String category = categoryEdit.getText().toString();
		String description = descriptionEdit.getText().toString();
		String dateCreate = dateEdit.getText().toString();
		if (lender.length() == 0 || borrower.length() == 0
				|| debt.length() == 0) {
			missing = "";
			if (lender.length() == 0) {
				missing += "Lender,";
			}
			if (borrower.length() == 0) {
				missing += "Borrower,";
			}
			if (debt.length() == 0) {
				missing += "Debt,";
			}
			missing = missing.substring(0, missing.length() - 1);
			showDialog(MY_ERROR_DIALOG);

		} else {
			ContentValues debtValues = new ContentValues();

			if (category.length() == 0) {
				category = "Uncategorized";
			}

			// Assign values for each row.
			debtValues.put(DebtAdapter._LENDER, lender);
			debtValues.put(DebtAdapter._BORROWER, borrower);
			debtValues.put(DebtAdapter._DEBT,
					String.format("%.2f", Double.parseDouble(debt)));
			debtValues.put(DebtAdapter._CATEGORY, category);
			debtValues.put(DebtAdapter._DESCRIPTION, description);
			debtValues.put(DebtAdapter._CREATE_DATE, dateCreate);
			debtAdapter.updateDebt(debtValues, debtId);
		}

	}

	private void pickContact(int request) {
		startActivityForResult(mContactAccessor.getPickContactIntent(), request);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if ((requestCode == LENDER_REQUEST || requestCode == BORROWER_REQUEST)
				&& resultCode == RESULT_OK) {
			loadContactInfo(data.getData(), requestCode);
		} else if (requestCode == CATEGORY_REQUEST && resultCode == RESULT_OK) {

			String item = data.getStringExtra("ItemId");
			Log.v("pickContact", item);

			categoryEdit.setText(item);
		}
	}

	private void loadContactInfo(Uri contactUri, final int request) {

		/*
		 * We should always run database queries on a background thread. The
		 * database may be locked by some process for a long time. If we locked
		 * up the UI thread while waiting for the query to come back, we might
		 * get an "Application Not Responding" dialog.
		 */
		AsyncTask<Uri, Void, ContactInfo> task = new AsyncTask<Uri, Void, ContactInfo>() {

			@Override
			protected ContactInfo doInBackground(Uri... uris) {
				return mContactAccessor.loadContact(getContentResolver(),
						uris[0]);
			}

			@Override
			protected void onPostExecute(ContactInfo result) {
				selectedContact = result;
				bindView(result, request);
			}
		};

		task.execute(contactUri);
	}

	private void bindView(ContactInfo contactInfo, int request) {
		if (request == LENDER_REQUEST) {
			lenderEdit.setText(contactInfo.getDisplayName());
		} else if (request == BORROWER_REQUEST) {
			borrowerEdit.setText(contactInfo.getDisplayName());
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case MY_ERROR_DIALOG:

			return new AlertDialog.Builder(this)
					.setTitle("Error")
					.setMessage("You have not enter a value for: " + missing)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
								}
							}).create();
		case MY_DATE_PICKER_DIALOG:
			DatePickerDialog dateDlg = new DatePickerDialog(this,
					new DatePickerDialog.OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							GregorianCalendar chosenDate = new GregorianCalendar(
									year, monthOfYear, dayOfMonth);

							dateEdit.setText(DateFormat.getDateInstance()
									.format(chosenDate.getTime()));

						}
					}, 2011, 1, 1);

			dateDlg.setMessage("When did this debt happen?");

			return dateDlg;

		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		switch (id) {
		case MY_ERROR_DIALOG:
			break;
		case MY_DATE_PICKER_DIALOG:
			DatePickerDialog dateDlg = (DatePickerDialog) dialog;
			Calendar cal = Calendar.getInstance();
			dateDlg.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
					cal.get(Calendar.DAY_OF_MONTH));

		}
	}

}